import React, { useState, useEffect } from 'react'
import { Layout, Typography, Alert, Spin } from 'antd'
import ChatBox from './components/ChatBox'
import ImageUploader from './components/ImageUploader'
import VoiceRecorder from './components/VoiceRecorder'
import './App.css'

const { Header, Content } = Layout
const { Title, Paragraph } = Typography

function App() {
  const [isLoading, setIsLoading] = useState(true)
  const [backendStatus, setBackendStatus] = useState(null)

  useEffect(() => {
    // 检查后端服务状态
    checkBackendStatus()
  }, [])

  const checkBackendStatus = async () => {
    try {
      const response = await fetch('http://localhost:8000/health')
      if (response.ok) {
        const data = await response.json()
        setBackendStatus({ status: 'online', data })
      } else {
        setBackendStatus({ status: 'offline', error: '后端服务不可用' })
      }
    } catch (error) {
      setBackendStatus({ status: 'offline', error: '无法连接到后端服务' })
    } finally {
      setIsLoading(false)
    }
  }

  if (isLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
      }}>
        <div style={{ textAlign: 'center', color: 'white' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16, fontSize: 18 }}>AI 智能客服助理启动中...</div>
        </div>
      </div>
    )
  }

  return (
    <div className="app-container">
      <Layout>
        <Header className="header">
          <Title level={2} style={{ color: '#1890ff', margin: 0 }}>
            🤖 AI 智能客服助理
          </Title>
          <Paragraph style={{ color: '#666', margin: '8px 0 0 0' }}>
            支持文字、语音、图片输入，智能识别发票并处理退款申请
          </Paragraph>

          {backendStatus && backendStatus.status === 'offline' && (
            <Alert
              message="后端服务连接失败"
              description={backendStatus.error}
              type="error"
              showIcon
              style={{ marginTop: 16 }}
            />
          )}
        </Header>

        <Content style={{ padding: '0 0 20px 0' }}>
          <div className="chat-container">
            <div className="chat-panel">
              <ChatBox backendStatus={backendStatus} />
            </div>

            <div className="sidebar">
              <ImageUploader />
              <VoiceRecorder />

              {backendStatus && backendStatus.status === 'online' && (
                <Alert
                  message="服务状态正常"
                  description={`后端版本: ${backendStatus.data?.version || '未知'}`}
                  type="success"
                  showIcon
                  style={{ marginTop: 16 }}
                />
              )}
            </div>
          </div>
        </Content>
      </Layout>
    </div>
  )
}

export default App
